<?php
/**
 * 任务队列类
 * @author Zeyes <lixize8888@163.com>
 * @link http://www.zeyes.org
 * @copyright (c) 2015-2017 DotTimes
 * @version 1.0
 */
require_once('Comm.class.php');
require_once('Db.class.php');

date_default_timezone_set('PRC');

class Queue
{
    private $db = null;
    /**
     * 添加任务到队列
     * @param string | array   $task 要执行的任务文件
     *        string | array   $param 附带的参数
     *        int       $priority 优先级，默认10
     * @return boolean 是否添加成功
     */
    public function addTask($task, $param = null, $priority = 10)
    {
        if(empty($db)) { $db = Comm::connDb(); $this->db = $db; }
        else $db = $this->db;
        if(is_array($task))
        {
            $sql = "INSERT INTO queue (task, param, priority) VALUES ";
            $c = count($task);
            for($i = 0; $i < $c; $i++)
            {
                if($i != 0) $sql .= ', ';
                $task[$i] = $db->quote($task[$i]);
                $param[$i] = $db->quote(json_encode($param[$i]));
                $sql .= "($task[$i], $param[$i], $priority)";
            }
            $sql .= ";";
            //echo $sql."\n";
            $count = $db->exec($sql);
            //print("Influenced $count rows.\n");
        }else
        {
            $sql = "INSERT INTO queue (task, param, priority) VALUES($task, $param, $priority);";
            $db->exec($sql);
            $id = $db->lastInsertId();
            return $id;
        }
        return true;
    }

    /**
     * 从队列获取任务
     * @param int $limit 最大获取的任务数量
     *        int $total 总进程数
     *        int $i     当前进程
     * @return array 任务数量
     */
    public function getTask($total = 1, $i = 0, $limit = 100)
    {
        $limit = (int)$limit;
        if(empty($db)) { $db = Comm::connDb(); $this->db = $db; }
        $sql = "SELECT id, task, param, priority FROM queue WHERE status=0 ".
            "AND id%$total=$i ORDER BY priority DESC, id ASC LIMIT $limit";
        $result = $db->query($sql);
        if(empty($result)) return ($result = array());
        foreach ($result as &$arr) {
            $arr['param'] = json_decode($arr['param'], true);
        }
        return $result;
    }

    /**
     * 更新任务状态
     * @param int $id 任务的id
     * @return boolean 是否执行成功
     */

    public function updateTask($id)
    {
        if(empty($db)) { $db = Comm::connDb(); $this->db = $db; }
        $sql = "UPDATE queue SET status=1 WHERE id=$id;";
        $db->exec($sql);
        $id = $db->lastInsertId();
        return $id;
    }
    
    /**
     * 清理已经执行的任务
     * @return boolean 是否执行成功
     */
    
    public function cleanTask()
    {
        if(empty($db)) { $db = Comm::connDb(); $this->db = $db; }
        $sql = "DELETE FROM queue WHERE status=1;";
        $db->exec($sql);
        return true;
    }
}

//$obj = new Queue();
//$obj->addTask('/aaa/aa.php', array('a'=>'a'), 20);
//$obj->getTask();
//$obj->cleanTask();
?>
